from image_utils import logging # 从image_utils.py中导入logging对象
<<<<<<< HEAD
import numpy as np
import cv2  # 添加cv2导入
=======
>>>>>>> 83d003ddee67f5cfc5d553312b9c70083f5e9fb2


def crop_image(image, crop_region):
    """
    裁剪图像
    :param image: 输入图像，PIL.Image对象
    :param crop_region: 裁剪区域,格式为(上,下,左,右)
    :return: 裁剪后的图像
    """
    try:
        logging.info(f"开始裁剪图像，裁剪区域,{crop_region}")
        
        # 从crop_region中提取上、下、左、右的坐标
        top, bottom, left, right = crop_region
        
        # 直接使用切片操作，裁剪图像 image 生成裁剪后的图像 cropped_image
        cropped_image = image[top:bottom, left:right]
        
        return cropped_image
    except Exception as e:
        raise ValueError(f"Error occurred while cropping image: {e}")
<<<<<<< HEAD


def adjust_brightness(image, factor):
    """
    调整图像亮度
    :param image: 输入图像，numpy数组
    :param factor: 亮度调整因子，0.0表示全黑，1.0表示原始亮度，2.0表示亮度加倍
    :return: 调整亮度后的图像
    """
    try:
        logging.info(f"调整图像亮度，因子: {factor}")
        adjusted_image = np.clip(image * factor, 0, 255).astype(np.uint8)
        return adjusted_image
    except Exception as e:
        raise ValueError(f"调整亮度时发生错误: {e}")


def apply_global_threshold(image, threshold):
    """
    应用全局阈值处理
    :param image: 输入图像，numpy数组
    :param threshold: 阈值
    :return: 阈值处理后的图像
    """
    try:
        logging.info(f"应用全局阈值处理，阈值: {threshold}")
        thresholded_image = (image > threshold).astype(np.uint8) * 255
        return thresholded_image
    except Exception as e:
        raise ValueError(f"应用全局阈值处理时发生错误: {e}")


def apply_shift_diff(image, shift):
    """
    应用移动差分
    :param image: 输入灰度图像，numpy数组
    :param shift: 移动的像素数，正值右移，负值左移
    :return: 移动差分后的图像
    """
    try:
        logging.info(f"应用移动差分，移动像素: {shift}")
        if shift == 0:
            return np.zeros_like(image)  # 如果不移动，返回全零图像
        shifted_image = np.roll(image, shift, axis=1)  # 沿水平方向移动
        diff_image = np.abs(image - shifted_image)  # 计算差分
        return diff_image
    except Exception as e:
        raise ValueError(f"应用移动差分时发生错误: {e}")


def apply_bitwise_and(image, mask):
    """应用与运算（遮罩）"""
    try:
        logging.info("应用与运算")
        return np.bitwise_and(image, mask)
    except Exception as e:
        raise ValueError(f"应用与运算时发生错误: {e}")

def apply_bitwise_or(image, mask):
    """应用或运算（融合）"""
    try:
        logging.info("应用或运算")
        return np.bitwise_or(image, mask)
    except Exception as e:
        raise ValueError(f"应用或运算时发生错误: {e}")

def apply_bitwise_not(image):
    """应用非运算（反转）"""
    try:
        logging.info("应用非运算")
        return np.bitwise_not(image)
    except Exception as e:
        raise ValueError(f"应用非运算时发生错误: {e}")

def generate_red_mask(image):
    """生成基于图像内容的红色掩膜"""
    try:
        logging.info("生成红色掩膜")
        if len(image.shape) != 3 or image.shape[2] != 3:
            raise ValueError("输入图像必须是RGB图像")

        # 转换为HSV颜色空间
        hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
        
        # 定义两个红色范围（HSV空间中红色在色相环的两端）
        lower_red1 = np.array([0, 120, 50])
        upper_red1 = np.array([10, 255, 255])
        lower_red2 = np.array([170, 120, 50])
        upper_red2 = np.array([180, 255, 255])
        
        # 创建掩膜
        mask1 = cv2.inRange(hsv, lower_red1, upper_red1)
        mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
        mask = cv2.bitwise_or(mask1, mask2)
        
        # 形态学操作改善掩膜质量
        kernel = np.ones((5,5), np.uint8)
        mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
        mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
        
        return mask

    except Exception as e:
        raise ValueError(f"生成红色掩膜时发生错误: {e}")


def generate_blue_mask(image):
    """生成基于图像内容的蓝色掩膜"""
    try:
        logging.info("生成蓝色掩膜")
        if len(image.shape) != 3 or image.shape[2] != 3:
            raise ValueError("输入图像必须是RGB图像")

        red_channel = image[:, :, 0]
        green_channel = image[:, :, 1]
        blue_channel = image[:, :, 2]

        # 蓝色掩膜条件：蓝色通道值大于红色和绿色通道值
        mask = (blue_channel > red_channel) & (blue_channel > green_channel)
        return (mask * 255).astype(np.uint8)
    except Exception as e:
        raise ValueError(f"生成蓝色掩膜时发生错误: {e}")


def generate_green_mask(image):
    """生成基于图像内容的绿色掩膜"""
    try:
        logging.info("生成绿色掩膜")
        if len(image.shape) != 3 or image.shape[2] != 3:
            raise ValueError("输入图像必须是RGB图像")

        red_channel = image[:, :, 0]
        green_channel = image[:, :, 1]
        blue_channel = image[:, :, 2]

        # 绿色掩膜条件：绿色通道值大于红色和蓝色通道值
        mask = (green_channel > red_channel) & (green_channel > blue_channel)
        return (mask * 255).astype(np.uint8)
    except Exception as e:
        raise ValueError(f"生成绿色掩膜时发生错误: {e}")


def apply_green_mask(image):
    """应用绿色掩膜"""
    try:
        mask = np.zeros_like(image)
        mask[:,:,1] = 255  # 绿色通道设为255
        return np.bitwise_and(image, mask)
    except Exception as e:
        raise ValueError(f"应用绿色掩膜时出错: {e}")

def apply_blue_mask(image):
    """应用蓝色掩膜"""
    try:
        mask = np.zeros_like(image)
        mask[:,:,2] = 255  # 蓝色通道设为255
        return np.bitwise_and(image, mask)
    except Exception as e:
        raise ValueError(f"应用蓝色掩膜时出错: {e}")
=======
    
>>>>>>> 83d003ddee67f5cfc5d553312b9c70083f5e9fb2
